package com.aviccxzx.smarthome.UserModule;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.aviccxzx.smarthome.R;
import com.aviccxzx.smarthome.entity.NewApkBean;
import com.aviccxzx.smarthome.fragment.CamFragment;
import com.aviccxzx.smarthome.fragment.DeviceListFragment;
import com.aviccxzx.smarthome.fragment.SceneFragment;
import com.aviccxzx.smarthome.fragment.SettingFragment;
import com.aviccxzx.smarthome.netutil.app.App;
import com.aviccxzx.smarthome.service.RetrofitHelper;
import com.aviccxzx.smarthome.service.RetrofitService;
import com.aviccxzx.smarthome.update.BaseAndroid;

import java.util.Timer;
import java.util.TimerTask;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by joey on 2017/4/7.
 */

public class MainAct extends FragmentActivity {
    // 布局管理
    private FragmentManager fManager;

    private DeviceListFragment fragment_home;
    private SceneFragment fragment_scene;
    private SettingFragment fragment_me;
    private CamFragment fragment_cam;

    // 首页
    private ImageView iv_menu_home;
    private TextView tv_menu_home;
    // 摄像头
    private ImageView iv_menu_cam;
    private TextView tv_menu_cam;

    // 场景
    private ImageView iv_menu_scene;
    private TextView tv_menu_scene;


    // 我的
    private ImageView iv_menu_me;
    private TextView tv_menu_me;

    /**
     * 上一次界面 onSaveInstanceState 之前的tab被选中的状态 key 和 value
     */
    private static final String PRV_SELINDEX = "PREV_SELINDEX";
    private int selindex = 0;
    /**
     * Fragment的TAG 用于解决app内存被回收之后导致的fragment重叠问题
     */
    private static final String[] FRAGMENT_TAG = {"home", "cam", "scene", "setting"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_lay);
        initStatebar();
        // 初始化组件
        initViews();

        if (savedInstanceState != null) {
            //读取上一次界面Save的时候tab选中的状态
            selindex = savedInstanceState.getInt(PRV_SELINDEX, selindex);
            fragment_home = (DeviceListFragment) fManager.findFragmentByTag(FRAGMENT_TAG[0]);
            fragment_cam = (CamFragment) fManager.findFragmentByTag(FRAGMENT_TAG[1]);
            fragment_scene = (SceneFragment) fManager.findFragmentByTag(FRAGMENT_TAG[2]);
            fragment_me = (SettingFragment) fManager.findFragmentByTag(FRAGMENT_TAG[3]);
        }
        // 选中index

        if (selindex == 0) {
            clickMenu(findViewById(R.id.ll_menu_home));
        } else if (selindex == 1) {
            clickMenu(findViewById(R.id.ll_menu_cam));
        } else if (selindex == 2) {
            clickMenu(findViewById(R.id.ll_menu_scene));
        } else {
            clickMenu(findViewById(R.id.ll_menu_me));
        }


        checkUpdate();
    }

    public void checkUpdate() {
        RetrofitService service = RetrofitHelper.getInstance(this).getServer();
        Call<NewApkBean> call = service.newestPack();
        call.enqueue(new Callback<NewApkBean>() {
            @Override
            public void onResponse(Call<NewApkBean> call, Response<NewApkBean> response) {
                if (response.body() != null && response.body().getData() != null) {
                    int versionSer = response.body().getData().getVersion();
                    String packurl = response.body().getData().getPackUrl();
                    if (versionSer > getVersion()) {
                        //需要升级
                        BaseAndroid.checkUpdate(MainAct.this, versionSer,
                                packurl, "中航安居APP有更新", true);
                    } else {
                        //最新版本
//                        showToast("已经是最新版本");
                    }
                }
            }

            @Override
            public void onFailure(Call<NewApkBean> call, Throwable t) {

            }
        });
    }

    //获取当前版本号
    private int getVersion() {
        try {
            PackageManager packageManager = getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }


    private void initStatebar() {
        //透明状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            // Translucent status bar
            window.setFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //保存tab选中的状态
        outState.putInt(PRV_SELINDEX, selindex);
        super.onSaveInstanceState(outState);
    }

    private void initViews() {
        // 布局管理器
        fManager = getSupportFragmentManager();

        iv_menu_home = (ImageView) findViewById(R.id.iv_menu_home);
        tv_menu_home = (TextView) findViewById(R.id.tv_menu_home);

        iv_menu_cam = (ImageView) findViewById(R.id.iv_menu_cam);
        tv_menu_cam = (TextView) findViewById(R.id.tv_menu_cam);

        iv_menu_scene = (ImageView) findViewById(R.id.iv_menu_scene);
        tv_menu_scene = (TextView) findViewById(R.id.tv_menu_scene);

        iv_menu_me = (ImageView) findViewById(R.id.iv_menu_me);
        tv_menu_me = (TextView) findViewById(R.id.tv_menu_me);
    }

    public void gotoDevice() {
        clickMenu(findViewById(R.id.ll_menu_home));
    }
    public void gotoCam() {
        clickMenu(findViewById(R.id.ll_menu_cam));
    }

    public void gotoScene() {
        clickMenu(findViewById(R.id.ll_menu_scene));
    }

    /**
     * 点击底部菜单事件
     *
     * @param v
     */
    public void clickMenu(View v) {
        FragmentTransaction trans = fManager.beginTransaction();
        int vID = v.getId();
        // 设置menu样式
        setMenuStyle(vID);
        // 隐藏所有的fragment
        hideFrament(trans);
        // 设置Fragment
        setFragment(vID, trans);
        trans.commit();
    }

    /**
     * 隐藏所有的fragment(编程初始化状态)
     *
     * @param trans
     */
    private void hideFrament(FragmentTransaction trans) {
        if (fragment_home != null) {
            trans.hide(fragment_home);
        }
        if (fragment_cam != null) {
            trans.hide(fragment_cam);
        }
        if (fragment_scene != null) {
            trans.hide(fragment_scene);
        }
        if (fragment_me != null) {
            trans.hide(fragment_me);
        }
    }

    /**
     * 设置menu样式
     *
     * @param vID
     * @param
     */
    private void setMenuStyle(int vID) {
        // 首页
        if (vID == R.id.ll_menu_home) {
            iv_menu_home.setImageDrawable(getResources().getDrawable(R.mipmap.tab_home_pre));
            tv_menu_home.setTextColor(getResources().getColor(R.color.title_common_color));
        } else {
            iv_menu_home.setImageDrawable(getResources().getDrawable(R.mipmap.tab_home));
            tv_menu_home.setTextColor(getResources().getColor(R.color.title_gray));
        }
        // 摄像头
        if (vID == R.id.ll_menu_cam) {
            iv_menu_cam.setImageDrawable(getResources().getDrawable(R.mipmap.tab_cam_pre));
            tv_menu_cam.setTextColor(getResources().getColor(R.color.title_common_color));
        } else {
            iv_menu_cam.setImageDrawable(getResources().getDrawable(R.mipmap.tab_cam));
            tv_menu_cam.setTextColor(getResources().getColor(R.color.title_gray));
        }
        // 场景
        if (vID == R.id.ll_menu_scene) {
            iv_menu_scene.setImageDrawable(getResources().getDrawable(R.mipmap.tab_scene_pre));
            tv_menu_scene.setTextColor(getResources().getColor(R.color.title_common_color));
        } else {
            iv_menu_scene.setImageDrawable(getResources().getDrawable(R.mipmap.tab_scene));
            tv_menu_scene.setTextColor(getResources().getColor(R.color.title_gray));
        }
        // 我的
        if (vID == R.id.ll_menu_me) {
            iv_menu_me.setImageDrawable(getResources().getDrawable(R.mipmap.tab_user_pre));
            tv_menu_me.setTextColor(getResources().getColor(R.color.title_common_color));
        } else {
            iv_menu_me.setImageDrawable(getResources().getDrawable(R.mipmap.tab_user));
            tv_menu_me.setTextColor(getResources().getColor(R.color.title_gray));
        }
    }


    /**
     * 设置Fragment
     *
     * @param vID
     * @param trans
     */
    private void setFragment(int vID, FragmentTransaction trans) {
        switch (vID) {
            case R.id.ll_menu_home:
                if (fragment_home == null) {
                    fragment_home = new DeviceListFragment();
                    trans.add(R.id.content, fragment_home, FRAGMENT_TAG[0]);
                } else {
                    trans.show(fragment_home);
                }
                break;
            case R.id.ll_menu_cam:
                if (fragment_cam == null) {
                    fragment_cam = new CamFragment();
                    trans.add(R.id.content, fragment_cam, FRAGMENT_TAG[1]);
                } else {
                    trans.show(fragment_cam);
                }
                break;
            case R.id.ll_menu_scene:
                if (fragment_scene == null) {
                    fragment_scene = new SceneFragment();
                    trans.add(R.id.content, fragment_scene, FRAGMENT_TAG[2]);
                } else {
                    trans.show(fragment_scene);
                }
                break;
            case R.id.ll_menu_me:
                if (fragment_me == null) {
                    fragment_me = new SettingFragment();
                    trans.add(R.id.content, fragment_me, FRAGMENT_TAG[3]);
                } else {
                    trans.show(fragment_me);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 菜单、返回键响应
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitBy2Click(); // 调用双击退出函数
        }
        return false;
    }

    /**
     * 双击退出函数
     */
    private static Boolean isExit = false;

    private void exitBy2Click() {
        Timer tExit = null;
        if (isExit == false) {
            isExit = true; // 准备退出
            String doubleClick = (String) getText(R.string.double_click);
            App.getApp().showToast(doubleClick);
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务

        } else {
            this.finish();
            //            System.exit(0);
        }
    }
}
